const express = require('express');
const axios = require('axios');
const cheerio = require('cheerio');
const cors = require('cors');

const app = express();
app.use(cors());
app.use(express.json());

// 模拟数据库
let booksDatabase = [];

// 数据采集端点
app.post('/api/scrape/books', async (req, res) => {
  try {
    const books = await scrapeBooksData();
    booksDatabase = books; // 存储到数据库
    res.json({ success: true, data: books });
  } catch (error) {
    res.status(500).json({ success: false, error: error.message });
  }
});

// 图书数据API
app.get('/api/books/recommended', (req, res) => {
  const recommended = booksDatabase.slice(0, 10);
  res.json({ data: recommended });
});

app.get('/api/books/new', (req, res) => {
  const newBooks = booksDatabase.slice(0, 8);
  res.json({ data: newBooks });
});

app.get('/api/books/hot', (req, res) => {
  const hotBooks = booksDatabase.slice(0, 6);
  res.json({ data: hotBooks });
});

app.get('/api/books/:id', (req, res) => {
  const book = booksDatabase.find(b => b.id == req.params.id);
  res.json({ data: book });
});

// 数据采集函数
async function scrapeBooksData() {
  const books = [];
  
  try {
    // 示例：爬取 books.toscrape.com
    const response = await axios.get('http://books.toscrape.com');
    const $ = cheerio.load(response.data);
    
    $('.product_pod').each((index, element) => {
      const title = $(element).find('h3 a').attr('title');
      const price = $(element).find('.price_color').text();
      const stock = $(element).find('.instock').text().includes('In stock') ? 10 : 0;
      
      books.push({
        id: index + 1,
        title: title || '未知标题',
        price: price.replace('£', '') || '0.00',
        stock: stock,
        cover: $(element).find('img').attr('src'),
        description: '图书描述信息...'
      });
    });
  } catch (error) {
    console.error('数据采集失败:', error);
    // 返回模拟数据作为备选
    return generateMockData();
  }
  
  return books;
}

// 生成模拟数据
function generateMockData() {
  return Array.from({ length: 20 }, (_, i) => ({
    id: i + 1,
    title: `图书标题 ${i + 1}`,
    price: (Math.random() * 50 + 10).toFixed(2),
    stock: Math.floor(Math.random() * 100),
    cover: `/static/book${(i % 5) + 1}.jpg`,
    description: `这是第 ${i + 1} 本图书的详细描述信息...`
  }));
}

app.listen(3000, () => {
  console.log('服务器运行在端口 3000');
});